<?php
/**
 * workerman
 * 启动命令：php server.php start -d
 * 平滑重启：php server.php reload
 * 重启：php server.php restart
 * 停止：php server.php stop
 * 查看状态：php server.php status
 */

namespace app\workerman\controller;

use think\facade\Config;
use think\facade\Env;
use Workerman\Lib\Timer;
use Workerman\Worker;

class WorkerMan {

    protected $processes;
    protected $worker;
    protected $cliCmd;
    protected $cache;
    protected $socket = '';
    protected $cachePrefix;
    protected $queue;

    /**
     * 架构函数
     * @access public
     */
    public function __construct() {
        //实例化 WebSocket 服务
        $this->worker = new Worker($this->socket);

        $this->cliCmd = $_SERVER['argv'][1];
        $this->cachePrefix = Config::get('cache.default')['prefix'];
        $this->queue = Config::pull('amqp')['queue'];

        //初始化
        if (!$this->init()) {
            return false;
        }

        //设置回调
        foreach (['onWorkerStart', 'onConnect', 'onMessage', 'onClose', 'onError', 'onBufferFull', 'onBufferDrain', 'onWorkerStop', 'onWorkerReload'] as $event) {
            if (method_exists($this, $event)) {
                $this->worker->$event = [$this, $event];
            }
        }

        //Run worker
        Worker::runAll();
    }

    /**
     * 初始化设置
     */
    public function init() {
        $this->processes = count($this->queue);
        $multiple = Env::get('workerman.multiple');

        //创建日志目录
        $runtime = Env::get('runtime_path');
        $pidPath = $runtime.'.run/';
        $logPath = $runtime .'workerman/';
        !is_dir($logPath) && mkdir($logPath, 0755, true);
        !is_dir($pidPath) && mkdir($pidPath, 0755, true);

        $this->worker->count = $this->processes * $multiple;
        $this->worker->name  = 'notification';
        Worker::$daemonize   = true;
        Worker::$logFile     = $logPath . 'workerman.log';
        Worker::$stdoutFile  = $logPath . 'workerman_stdout.log';
        Worker::$pidFile     = $pidPath . 'workerman.pid';

        return true;
    }
    /**
     * 每个子进程启动
     * 子进程里面的代码可以用 php workerman.php reload 平滑重启
     * @param $worker
     */
    public function onWorkerStart($worker) {
        $queueId = $worker->id % $this->processes;
        $queueName = $this->queue[$queueId];
        Timer::add(0.8, [$this, 'notification'], [$queueName]);
//        $this->notification($queueName);
    }

    /**
     * @desc 多进程订单通知
     * @param $part
     * @return mixed
     */
    public function notification($part) {
        return model('WorkerMan', 'logic')->handleOnce($part);
    }
}